// data-set 可以按需引入，除此之外不要引入别的包
import React from 'react';
import { Chart, Axis, Tooltip, Geom, Legend } from 'bizcharts';
import DataSet from '@antv/data-set';


// 下面的代码会被作为 cdn script 注入 注释勿删
// CDN START

const ds = new DataSet();

const scale = {
  r: {
    type: 'linear',
    min: 0,
    max: 10,
  },
};

let chartIns = null;

const getG2Instance = (chart) => {
  chartIns = chart;
};

class CiaxCharts extends React.Component {
  render() {
    const { data } = this.props;
    const dv = ds.createView().source(data);
    dv.transform({
      type: 'fold',
      fields: ['男', '女'], // 展开字段集
      key: 'type', // key字段
      value: 'value', // value字段
    });
    return (<Chart
        // height={300}
        // width={350}
        height={280}
        width={window.innerWidth-30}
        forceFit
        data={dv}
        scale={scale}
        padding={[24, 'auto', 'auto', 'auto']}
        onGetG2Instance={getG2Instance}>
      <Legend
        custom
        allowAllCanceled
        items={[
          { value: '男', marker: { symbol: 'square', fill: '#3182bd', radius: 5 } },
          { value: '女', marker: { symbol: 'square', fill: '#41a2fc', radius: 5 } },
          { value: '男女比例', marker: { symbol: 'hyphen', stroke: '#fad248', radius: 5, lineWidth: 3 } },
        ]}
        onClick={(ev) => {
          const item = ev.item;
          const value = item.value;
          const checked = ev.checked;
          const geoms = chartIns.getAllGeoms();
          for (let i = 0; i < geoms.length; i++) {
            const geom = geoms[i];
            if (geom.getYScale().field === value && value === '男女比例') {
              if (checked) {
                geom.show();
              } else {
                geom.hide();
              }
            } else if (geom.getYScale().field === 'value' && value !== '男女比例') {
              geom.getShapes().map((shape) => {
                if (shape._cfg.origin._origin.type == value) {
                  shape._cfg.visible = !shape._cfg.visible;
                }
                shape.get('canvas').draw();
                return shape;
              });
            }
          }
        }}
      />
      <Axis name="label" />
      <Axis name="value" position={'left'} />
      <Tooltip />
      <Geom
        type="interval"
        position="label*value"
        color={['type', (value) => {
          if (value === '男') {
            return '#2b6cbb';
          }
          if (value === '女') {
            return '#41a2fc';
          }
        }]}
        adjust={[{
          type: 'dodge',
          marginRatio: 1 / 32,
        }]}
      />
      <Geom type="line" position="label*男女比例" color="#fad248" size={3} />
    </Chart>
    );
  }
}

// CDN END
export default CiaxCharts;
